package com.demo.util;

import java.io.IOException;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.Assert;
import org.springframework.util.ConcurrentReferenceHashMap;
import org.springframework.util.StringUtils;

/**
 * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
 */
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
	// org.springframework.web.context.support.SpringBeanAutowiringSupport
	
	public static final String MAIN_NAME = "main";

	private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);
	private static Map<String, ApplicationContext> nameToApplicationContext = new ConcurrentReferenceHashMap<String, ApplicationContext>();

	/**
	 * The main applicationContext object for system
	 */
	private static ApplicationContext applicationContext = null;
	private static ResourcePatternResolver resolver = null;

	private String name;

	public SpringContextHolder() {
		super();
	}

	public SpringContextHolder(String name) {
		this.name = name;
	}

	public static ApplicationContext use() {
		return use(MAIN_NAME);
	}

	public static ApplicationContext use(String name) {
		return nameToApplicationContext.get(name);
	}

	public static void addApplicationContext(String name, ApplicationContext applicationContext) {
		Assert.notNull(name, "name 不能为 null .");
		Assert.notNull(applicationContext, "ApplicationContext 不能为 null .");
		logger.debug("注入 ApplicationContext[{}] 到 SpringContextHolder :{}", name, applicationContext);
		if (nameToApplicationContext.containsKey(name)) {
			logger.info("SpringContextHolder 中的 ApplicationContext 被覆盖, 原有ApplicationContext[{}]为:", name,
					SpringContextHolder.applicationContext);
		}

		nameToApplicationContext.put(name, applicationContext);

		/** 
		 * Replace the main applicationContext if current applicationContext name is MAIN_NAME
		 */
		if (MAIN_NAME.equals(name)) SpringContextHolder.applicationContext = applicationContext;

		/**
		 * The name may not be MAIN_NAME,
		 * the main applicationContext have to set the first comming ApplicationContext if it is null
		 */
		if (SpringContextHolder.applicationContext == null) SpringContextHolder.applicationContext = applicationContext;
	}

	/**
	 * 取得存储在静态变量中的ApplicationContext.
	 */
	public static ApplicationContext getApplicationContext() {
		validContextInjected();
		return applicationContext;
	}

	/**
	 * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
		return (T) getApplicationContext().getBean(name);
	}

	/**
	 * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
	 */
	public static <T> T getBean(Class<T> requiredType) {
		return getApplicationContext().getBean(requiredType);
	}

	/**
	 * 清除SpringContextHolder中的ApplicationContext为Null.
	 */
	public static void clearHolder() {
		if (logger.isDebugEnabled()) {
			logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
		}
		applicationContext = null;
	}

	/**
	 * 实现ApplicationContextAware接口, 注入Context到静态变量中.
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		if (StringUtils.isEmpty(name)) {
			name = MAIN_NAME;
		}
		addApplicationContext(name, applicationContext);
	}

	/**
	 * 实现DisposableBean接口, 在Context关闭时清理静态变量.
	 */
	@Override
	public void destroy() throws Exception {
		SpringContextHolder.clearHolder();
	}

	/**
	 * 检查ApplicationContext不为空.
	 */
	private static void validContextInjected() {
		Assert.notNull(applicationContext, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
	}

	public static void setResolver(ResourcePatternResolver resolver) {
		SpringContextHolder.resolver = resolver;
	}

	public static ResourcePatternResolver getResolver() {
		if (resolver == null) {//
			if (applicationContext == null) {//
				resolver = new PathMatchingResourcePatternResolver();
			} else {
				resolver = applicationContext;
			}
		}

		return resolver;
	}

	public static Resource getResource(String location) {
		return getResolver().getResource(location);
	}

	public static ClassLoader getClassLoader() {
		return getResolver().getClassLoader();
	}

	public static Resource[] getResources(String locationPattern) throws IOException {
		return getResolver().getResources(locationPattern);
	}
}